package edu.ucsd.ccdb.tagPopup;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import edu.ucsd.ccdb.DetailPanel;
import edu.ucsd.ccdb.MainConfiguration;
import edu.ucsd.ccdb.generalDataType.DataValue;
import edu.ucsd.ccdb.generalDataType.PurposeValue;
import edu.ucsd.ccdb.servlet.ServletSendReceive;
import edu.ucsd.ccdb.tagPopup.dataType.CCDBDescription;
import edu.ucsd.ccdb.tagPopup.summaryPane.CCDBTagSummaryPane;
import edu.ucsd.ccdb.tagPopup.summaryPane.OnthoTagSummaryPane;
import edu.ucsd.ccdb.tagPopup.util.DetailViewAutoRefresh;
import edu.ucsd.ccdb.tagPopup.util.SummaryPaneRefresher;
import edu.ucsd.irods.IRODSFileString;
import edu.ucsd.irods.SQLDBQuery;

public class TagDialog extends JDialog implements ActionListener{
	

	private static final long serialVersionUID = 1L;
	
	private Integer MPID ; 
	private JButton addButton;
	private IRODSFileString file;
	
	private JPanel summuryPane;
	private JComboBox listPurposeID;
	private JComboBox listDataID ;
	
	private String username ;
	
	private JPanel detailView;
	
	private JFrame mainFrame;
	private List<String> clickedFile;
	private String baseFolder;
	
	public TagDialog (String username, JFrame parent, IRODSFileString file, Integer MPID, JPanel detailView, String baseFolder, List<String> clickedFile ) {
		
		super (parent, "Tag Manager: " + file.getName() );
		this.username = username;
		this.file = file;
		this.MPID = MPID;
		this.mainFrame = parent;
		this.clickedFile = clickedFile;
		
		this.detailView = detailView;
		this.baseFolder = baseFolder;
		
		JTabbedPane parentTabPane = new JTabbedPane ();

		summuryPane = new JPanel();
		summuryPane.setLayout(new BoxLayout(summuryPane, BoxLayout.Y_AXIS ));
		
		try {
			parentTabPane.addTab("CCDB", new CCDBTab() );
			parentTabPane.addTab("Onto", new OnthoTab ( detailView, mainFrame, baseFolder, clickedFile, username, MPID, file, summuryPane, this)  );
			parentTabPane.addTab("Note", new NoteTab( file.getAbsolutePath() ) );					
		}
		catch (Exception e){
			e.printStackTrace();
		}

		JPanel CCDBPane = new CCDBTagSummaryPane( username, summuryPane, MPID, file);
		JPanel onthoPane = new OnthoTagSummaryPane ( username, summuryPane, MPID, file );
		
//		JButton buttonTest = new JButton ("Refresh");
//		buttonTest.addActionListener(new SummaryPaneRefresher( username, MPID, file, this.summuryPane));
		
        summuryPane.add(CCDBPane);
        summuryPane.add(onthoPane);
//        summuryPane.add(buttonTest);		
		
		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
		JScrollPane scrollPane = new JScrollPane( summuryPane);
		
		scrollPane.setPreferredSize(new Dimension(400, 200) );
		Dimension tabSize = new Dimension(400,175);
		parentTabPane.setMinimumSize(tabSize);
		parentTabPane.setPreferredSize(tabSize);
		
		splitPane.setTopComponent( scrollPane );
		splitPane.setBottomComponent(parentTabPane);
		splitPane.setResizeWeight(1.0);	// this for when resizing, the top resize and not the bottom

		add (splitPane, BorderLayout.CENTER);
		
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		addWindowListener(new DetailViewAutoRefresh(detailView, username, file, mainFrame, MPID, baseFolder, clickedFile) );
	}

	/**
	 * (non-Javadoc) This to apply CCDB tag when clicking the "Add" button
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {

		System.out.println ("Try to refresh");
		
		//process, send the 2 drop down to be processed s 
		try {
			if (listPurposeID.getItemCount() > 0 && listDataID.getItemCount() >0 ) {

				SQLDBQuery.manageInsertCCDBTag( MPID, file, (PurposeValue) listPurposeID.getSelectedItem(), 
											(DataValue) listDataID.getSelectedItem() );
				
				if (file.isDirectory() ) {
						
					Queue<IRODSFileString> queue = new PriorityQueue<IRODSFileString>(); 
					queue.offer(file);
					
					IRODSFileString iterateFile = null;					
					while ( (iterateFile = queue.poll() ) != null ) {
					
						String query = MainConfiguration.SERVLET_SERVER + MainConfiguration.SERVLET_PARAMETER + iterateFile.getAbsolutePath();
						List<IRODSFileString> listFiles = ServletSendReceive.getResponse( query );
						
						for (IRODSFileString element: listFiles ) {
															
							if (element.isDirectory() )
								queue.offer(element);
							
							// apply tags to all level 1 children
							SQLDBQuery.manageInsertCCDBTag(MPID, element, (PurposeValue) listPurposeID.getSelectedItem(), 
									(DataValue) listDataID.getSelectedItem());
						}
					}
				}
			}
			else
				System.err.println ("One of the 2 drop down is empty");
		}
		catch (SQLException e1) {
			e1.printStackTrace();
		}
		catch (Exception e2) {
			e2.printStackTrace();
		}
		
		// do refresh here 
		SummaryPaneRefresher.doRefreshAction( username, MPID, file, summuryPane);

		int n = JOptionPane.showConfirmDialog(this, "Tag successfully added. Would you like add more tags ?", 
												"Confirm box", JOptionPane.YES_NO_OPTION);
		
		if (n == JOptionPane.NO_OPTION ) {
			// set invisible the panel
			this.setVisible(false);
			
			//Refresh the view panel upon returning from this panel
			DetailViewAutoRefresh.refreshDetailView_static(detailView, username, file, mainFrame, MPID, baseFolder, clickedFile);
		}
	}
	
//	private class RefreshDetailViewWhenExit extends WindowAdapter {
//		@Override 
//		public void windowClosed (WindowEvent e) {
//			System.out.println ("Dialog closed ");		
//			refreshDetailView();
//		}
//		
//		@Override
//		public void windowClosing (WindowEvent e) {
//			System.out.println ("Dialog closing");	
//			refreshDetailView();
//		}
//
//		/**
//		 * Refresh the detail view
//		 */
//		public void refreshDetailView () {
//			
//			detailView.removeAll();
//			detailView.add(new DetailPanel(username, file, mainFrame, MPID, baseFolder, clickedFile ) );
//			
////			detailView.add(new DetailPanel( username, file, mainFrame, MPID, pathTextField.getText(), listFileClicked ));
//			
//			detailView.validate();
//			detailView.repaint();
//		}
//	}
	
	private class CCDBTab extends JPanel implements ActionListener  {

		private static final long serialVersionUID = 1L;
		List<PurposeValue> listOfPurposes ;
		Map<Integer, List<DataValue> > mapDataSectionID;
		
		DefaultComboBoxModel comboBoxModel;
		JTextArea descriptionText;

		public CCDBTab ( ) throws Exception {
			
			setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
			setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
			
			// some instructions to users
			JLabel instructionLabel = new JLabel();
			instructionLabel.setText("You must select both drop downs: ");
			instructionLabel.setAlignmentX(RIGHT_ALIGNMENT);
			
			// put on the list
			listOfPurposes = SQLDBQuery.getDropDownList ();
			
			Collections.sort(listOfPurposes, new PurposeValue.PurposeValueComparator() );	// sort the list
			
			listPurposeID = new JComboBox( listOfPurposes.toArray() );
			listPurposeID.addActionListener(this);
			comboBoxModel = new DefaultComboBoxModel();
			listDataID = new JComboBox( comboBoxModel );
			listDataID.addActionListener(new CCDBIDDescriptionAction());
			
			JLabel dataTypeLabel = new JLabel("Data Type: ");
			JLabel CCDB_IDLabel = new JLabel("CCDBID: ");
			
			JPanel dataTypePane = new JPanel();
			dataTypePane.setLayout(new BoxLayout(dataTypePane, BoxLayout.X_AXIS ));
			dataTypePane.setAlignmentX(CENTER_ALIGNMENT);
			
			dataTypePane.add(dataTypeLabel);
			dataTypePane.add(listPurposeID);
			
			JPanel CCDBPane = new JPanel();
			CCDBPane.setLayout(new BoxLayout(CCDBPane, BoxLayout.X_AXIS));
			CCDBPane.setAlignmentX(CENTER_ALIGNMENT);
			
			descriptionText = new JTextArea( 10, 5 );
			descriptionText.setEditable(false);
			
			addButton = new JButton ("Add");
			addButton.addActionListener( TagDialog.this );
//			addButton.addActionListener(new SummaryPaneRefresher(MPID, file, TagDialog.this.summuryPane));
			addButton.setEnabled(false);
			addButton.setAlignmentX(CENTER_ALIGNMENT);
			
			CCDBPane.add(CCDB_IDLabel);
			CCDBPane.add(listDataID);
			
			// add to the main Panel
			add (instructionLabel);
			add (Box.createRigidArea(new Dimension(0,5) ));
			add (dataTypePane);
			add (Box.createRigidArea(new Dimension(0,5)));
			add (CCDBPane);
			add (Box.createRigidArea(new Dimension (0, 5)));
			add (new JScrollPane( descriptionText ) );
			add (Box.createRigidArea(new Dimension (0, 5)));
			add (addButton);
			
		}
		
		/**
		 * This for the first drop down to be selected 
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 * 
		 */
		public void actionPerformed(ActionEvent e) {
			
			System.out.print ("Choose thing in combo box.");
			
			JComboBox cb = (JComboBox) e.getSource();
			PurposeValue selectedItem = ( PurposeValue ) cb.getSelectedItem();
			
			System.out.println ("I choose: " + selectedItem);
			
			comboBoxModel.removeAllElements();
			
			try {
				mapDataSectionID = SQLDBQuery.getDataSectionID(username);
				List<DataValue> listData = mapDataSectionID.get(MPID);
				
				if (listData != null ) {	// safeguard against null pointer where nothing 
				
					for (DataValue element: listData ){
						if ( element.getType() == selectedItem.getType() )
							comboBoxModel.addElement(element);
					}
				}
			
				if (comboBoxModel.getSize() > 0 ) {
					addButton.setEnabled(true);
				}
				else {
					addButton.setEnabled(false);					
				}
				
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
		/**
		 * This is for when the second drop down is selected. Then go fill the description box
		 */
		private class CCDBIDDescriptionAction implements ActionListener {

			public void actionPerformed(ActionEvent e) {
				JComboBox cb = (JComboBox) e.getSource();
				
				DataValue data = (DataValue) cb.getSelectedItem();
				if ( data != null) {
					try {
						CCDBDescription description = SQLDBQuery.getCCDBIDDescription( data.getValue() );
						
						descriptionText.setText( description == null ? "No description" : description.toString() );
					} catch (SQLException e1) {
						descriptionText.setText("Error retrieving description");
						e1.printStackTrace();						
					}
				}
			}
		}
	}

}
